import json
from datetime import datetime
import os
import uuid
import xlrd
import openpyxl
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.paginator import Paginator
from django.db.models import Q
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from isi_api.settings import API_HOST, BASE_DIR

from baseinfo.helpfun import query_to_list, feedback_filter, feedback_to_excelpath
from feedback.models import FeedBack


def hello(request):
    return HttpResponse('hello test')

# 添加经验反馈


def add_feedback(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        feedback = FeedBack()
        feedback.outage = data['outage']
        feedback.team = data['team']
        feedback.title = data['title']
        feedback.detail = data['detail']
        feedback.occurDate = datetime.strptime(
            data['occurDate'], '%Y-%m-%d').date()
        feedback.reason = data['reason']
        feedback.measure = data['measure']
        token = request.META.get("HTTP_AUTHORIZATION")
        user_id = cache.get(token)
        user = User.objects.filter(pk=user_id)[0]
        feedback.create_user = user.username
        feedback.save()
        res = {
            'data': None,
            'meta': {'status': 200, 'message': '添加经验反馈成功'}
        }
        return JsonResponse(res)

# 获取经验反馈列表


def get_feedback(request):
    if request.method == 'GET':
        queryInfo = request.GET
        pagesize = queryInfo.get('pagesize')
        pagenum = queryInfo.get('pagenum')
        feedbacks = feedback_filter(queryInfo)
        total = feedbacks.count()
        if total:
            paginator = Paginator(feedbacks, pagesize)
            num_pages = paginator.num_pages
            if int(pagenum) > num_pages:
                pagenum = 1
            page_feedbacks = paginator.page(pagenum)
            page_feedbacks = query_to_list(page_feedbacks)
            data = {
                'page_feedbacks': page_feedbacks,
                'total': total,
                'pagenum': pagenum
            }
            res = {
                'data': data,
                'meta': {'status': 200, 'message': '获取经验反馈列表成功！'}
            }
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '未查询到相关数据'}
            }
        return JsonResponse(res)

# 根据id删除经验反馈


def delete_feedback(request, feedback_id):
    if request.method == "DELETE":
        feedback = FeedBack.objects.get(pk=feedback_id)
        feedback.is_delete = True
        feedback.save()
        res = {
            'data': None,
            'meta': {'status': 200, 'message': '经验反馈删除成功！'}
        }
        return JsonResponse(res)

# 根据id编辑经验反馈


def edit_feedback(request, feedback_id):
    if request.method == 'GET':
        feedback = FeedBack.objects.get(pk=feedback_id)
        res = {
            'data': {'feedback': model_to_dict(feedback)},
            'meta': {'status': 200, 'message': '获取待编辑的经验反馈信息成功'}
        }
        return JsonResponse(res)
    elif request.method == 'PUT':
        data = json.loads(request.body)
        try:
            feedback_id = data.get('id')
            feedback = FeedBack.objects.get(pk=feedback_id)
            feedback.outage = data.get('outage')
            feedback.team = data.get('team')
            feedback.title = data.get('title')
            feedback.detail = data.get('detail')
            feedback.occurDate = datetime.strptime(
                data.get('occurDate'), '%Y-%m-%d').date()
            feedback.reason = data.get('reason')
            feedback.measure = data.get('measure')
            feedback.save()
            res = {
                'data': None,
                'meta': {'status': 200, 'message': '经验反馈信息修改成功！'}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 801, 'message': '经验反馈信息修改失败！'}
            }
        return JsonResponse(res)


# 经验反馈导出excel
def export_to_excel(request):
    queryInfo = request.GET
    feedbacks = feedback_filter(queryInfo)
    excel_url = feedback_to_excelpath(feedbacks)

    res = {
        'data': {'excel_url': excel_url},
        'meta': {'status': 200, 'message': '经验反馈导出EXCEL成功'}
    }
    return JsonResponse(res)

# 已经优化：从静态资源地址直接获取Excel
# 下载经验反馈导入模板
# def feedback_template(request):
#     relative_path = '/media/excel/经验反馈导入模板.xlsx'
#     excel_url = BASE_DIR + relative_path
#     res = {
#         'data': {'excel_url': excel_url},
#         'meta': {'status': 200, 'message': '经验反馈模板下载成功'}
#     }
#     return JsonResponse(res)

# 读取上传的经验反馈excel


def upload_excel(request):
    if request.method == 'POST':
        file = request.FILES.get('feedbackExcel')
        # shortpath = os.path.join('media/feedbacktemp',
        #                          uuid.uuid4().hex + file.name)
        # print(shortpath)
        # with open(shortpath, 'wb') as temp_file:
        #     for chunk in file:
        #         temp_file.write(chunk)
        #     temp_file.flush()

        # wb = xlrd.open_workbook(shortpath)
        # ws = wb.sheet_by_index(0)
        # titles = ws.row_values(0)
        feedbacks = []
        wb = openpyxl.load_workbook(file)
        sheetnames = wb.sheetnames
        ws = wb[sheetnames[0]]
        if ws['A1'].value != '序号' or ws['B1'].value != '大修轮次' or ws['C1'].value != '项目组' or ws['D1'].value != '事件标题' or ws['E1'].value != '事件描述' or ws['F1'].value != '发生日期' or ws['G1'].value != '原因分析' or ws['H1'].value != '反馈措施' or ws['I1'].value != '录入人':
            res = {
                'data': {},
                'meta': {'status': 201, 'message': "导入的表格格式错误，请下载使用标准模板"}
            }
            return JsonResponse(res)
        for row in ws.values:
            if row[0] == '' or row[0] == '序号':
                pass
            else:
                feedback = {}
                feedback["outage"] = row[1]
                feedback["team"] = row[2]
                feedback["title"] = row[3]
                feedback["detail"] = row[4]
                # 数据类型是datetime.datetime(2021, 1, 1, 0, 0)
                # feedback["occurDate"] = row[5]
                feedback["occurDate"] = datetime.strftime(row[5], '%Y-%m-%d')
                feedback["reason"] = row[6]
                feedback["measure"] = row[7]
                feedback["create_user"] = row[8]
                results = FeedBack.objects.filter(
                    outage=row[1]).filter(title=row[3])
                if results.count():
                    feedback['is_repeat'] = "是"
                else:
                    feedback['is_repeat'] = "否"
                feedbacks.append(feedback)
        res = {
            'data': {'feedbacks': feedbacks},
            'meta': {'status': 200, 'message': "成功读取经验反馈表格！"}
        }
        return JsonResponse(res)

# 读取excel后的经验反馈点击确认上传按钮后保存到数据库


def save_feedbacks(request):
    if request.method == 'POST':
        feedbacks = json.loads(request.body)
        saved = 0
        ignored = 0
        for feedback in feedbacks:
            if feedback['is_repeat'] == '否':
                new_feedback = FeedBack()
                new_feedback.outage = feedback['outage']
                new_feedback.team = feedback['team']
                new_feedback.title = feedback['title']
                new_feedback.detail = feedback['detail']
                new_feedback.occurDate = datetime.strptime(
                    feedback['occurDate'], '%Y-%m-%d')
                new_feedback.reason = feedback['reason']
                new_feedback.measure = feedback['measure']
                new_feedback.create_user = feedback['create_user']
                new_feedback.save()
                print(new_feedback)
                saved = saved + 1
            else:
                ignored = ignored + 1

        res = {
            'data': {'saved': saved, 'ignored': ignored},
            'meta': {'status': 200, 'message': "保存经验反馈数据成功！"}
        }
        return JsonResponse(res)
